<template>
    <div class="f-table">
        <table>
            <colgroup>
                <!-- 控制每一列的宽度 -->
                <col :width="th?.width" v-for="th in columList">
            </colgroup>
            <thead>
                <!-- 标题 -->
                <th v-for="th in columList" :colspan="1" :rowspan="1" :style="{ textAlign: th.align }">
                    {{ th?.label }}
                </th>
            </thead>
            <tbody>
                <!-- 行 -->
                <tr v-for="row in data" v-if="data?.length">
                    <!-- 列 -->
                    <td v-for="td in columList" :style="{ textAlign: td.align }">
                        <!-- 打印属性的值 -->
                        {{ row[td?.prop] }}
                    </td>
                </tr>
                <!-- 空数据 -->
                <tr class="no-data" v-else>
                    <td :colspan="columList.length">
                        暂无数据
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, useSlots } from 'vue';
import type { PropsType } from "./f-table-colum/index.vue";

withDefaults(defineProps<{
    /** 表数据 */
    data: any[]
}>(), {
    data: [] as any
})

/** 列数据 */
const columList = reactive<PropsType[]>([])

// 初始化列
function InitColum() {
    const slots = useSlots().default
    if (slots && slots()) {
        // 得到所有插槽数据
        for (const slot of slots()) {
            let col: any = slot
            // 名字为 FTableColum 组件插槽
            if (col.type.name && col.type.name === "FTableColum") {
                if (col.props) {
                    columList.push(col.props)
                }
            }
        }
    }
}

onMounted(() => {
    InitColum()
})

defineOptions({
    name: "FTable"
})

</script>

<style lang="scss" scoped>
.f-table {
    box-sizing: border-box;
    padding: 10px;
    width: 100%;
    display: flex;
    overflow: auto;
}

table {
    width: 100%;
    border-collapse: collapse;
    text-align: left;
    table-layout: fixed;

    th,
    td {
        border: 0;
        box-sizing: border-box;
        padding: 12px;
        line-height: 24px;
    }

    tbody {
        tr:hover {
            background-color: #F2F3F5;
        }

        td {
            overflow: hidden;
            font-size: 14px;
            border-top: 1px solid #DCDFE6;
            border-bottom: 1px solid #DCDFE6;
        }

        .no-data {
            height: 50px;
            color: gray;
            text-align: center;
        }
    }
}
</style>